﻿using System;
using System.IO;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ThreeDWorld
{
    public class SpriteFont : IDisposable
    {
        private Rectangle[] _Rectangles;
        private Texture2D _Texture;

        public SpriteFont(ContentReader reader)
        {
            BitmapImage image = new BitmapImage();
            MemoryStream stream = null;

            _Rectangles = reader.ReadRectangleArray();

            try
            {
                image.SetSource(stream = new MemoryStream(reader.ReadByteArray()));
                _Texture = new Texture2D(reader.Content.Game.GraphicsDevice, image.PixelWidth, image.PixelHeight, false, SurfaceFormat.Color);
                image.CopyTo(_Texture);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }

        public Vector2 MeasureText(string text)
        {
            Vector2 size = Vector2.Zero;

            for (int i = 0; i != text.Length; i++)
            {
                int j = (int)text[i] - 32;

                if (j < 0 || j >= _Rectangles.Length)
                {
                    continue;
                }

                Rectangle r = _Rectangles[j];

                size.X += r.Width;
                if (r.Height > size.Y)
                {
                    size.Y = r.Height;
                }
            }
            return size;
        }

        internal void DrawText(SpriteBatch spriteBatch, string text, Vector2 position, Vector3 color, float alpha)
        {
            Rectangle r;

            for (int i = 0; i != text.Length; i++)
            {
                int j = (int)text[i] - 32;

                if (j < 0 || j >= _Rectangles.Length)
                {
                    continue;
                }

                r = _Rectangles[j];

                spriteBatch.Draw(_Texture, position, new Vector2(r.Width, r.Height), r, color, alpha);

                position.X += r.Width;
            }
        }

        public void Dispose()
        {
            if (!_Texture.IsDisposed)
            {
                _Texture.Dispose();
            }
        }
    }
}
